import axiosInstance from './index';
import { message } from 'antd';
import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { Response } from '@/types/responseTypes';
import store from '@/store/index'
import { createLoading  } from '@/store/actionTypes/actionCreator'

/**
 * 请求，包装一层，这里做拦截器特殊情况的处理
 * @returns 
 */
export const wrapRequest = (eject: boolean = false) => {
	const instance = axiosInstance();
	const requestInterceptor = instance.interceptors.request.use(
		(config: AxiosRequestConfig) => {
			// 请求拦截器
			//todo  请求头token。。。
			console.log('=====');
			const token = localStorage.getItem('mockToken');
			const productId: string = localStorage.getItem('productId') || '';

			config.headers!.Authorization = 'Basic-' + token;
			config.headers!['product-id'] = productId;

			// 发送请求时显示loading
			store.dispatch(createLoading(true))
			return config;
		},
		(err) => {
			return Promise.reject(err);
		}
	);
	const responseInterceptor = instance.interceptors.response.use(
		(response) => {
			store.dispatch(createLoading(false))
			// 响应拦截器
			// 响应判断：提示信息等
			const { status, statusText, data } = response;
			if (status !== 200) {
				return message.error(statusText);
			}
			return data;
		},
		(err) => {
			store.dispatch(createLoading(false))
			return Promise.reject(err);
		}
	);
	// 如果传入eject 则删除当前拦截器
	if (eject) {
		instance.interceptors.request.eject(requestInterceptor);
		instance.interceptors.response.eject(responseInterceptor);
	}
	return instance;
};

class Http {
	service;
	constructor(instance: AxiosInstance) {
		this.service = instance;
	}
	get<T>(url: string, params?: object, _object = {}): Promise<Response<T>> {
		return this.service.get(url, { params, ..._object });
	}
	post<T>(url: string, params?: object, _object = {}): Promise<Response<T>> {
		return this.service.post(url, params, _object);
	}
	put<T>(url: string, params?: object, _object = {}): Promise<Response<T>> {
		return this.service.put(url, params, _object);
	}
	delete<T>(url: string, params?: any, _object = {}): Promise<Response<T>> {
		return this.service.delete(url, { params, ..._object });
	}
}

// 默认使用这个请求，如果有其他需求可以使用wrapRequest进行包装处理
export default new Http(wrapRequest());
